package com.redis.controller;

import com.redis.config.JedisUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author chenzhangkun
 * @ClassName WatchController
 * @description: TODO
 * @date 2024年11月06日
 */
@RestController
@RequestMapping(value = "/redis/watch")
public class WatchController {

	@Resource
	private JedisUtils jedisUtils;
	@GetMapping("/demo/{key}")
	public Integer watch(@PathVariable("key") String key){
		Jedis jedis = jedisUtils.getJedis();
		while (true){
			// 监听key
			jedis.watch(key);
			int i = Integer.parseInt(jedis.get(key));
			i*=2;
			// 开启事务，redis事务只有隔离性，并没有原子性
			Transaction transaction = jedis.multi();
			transaction.set(key, String.valueOf(i));
			// 执行事务，如果此时key被其他客户端修改，此时会返回null
			List<Object> exec = transaction.exec();
			if (exec!=null){
				// 更新成功
				break;
			}
		}
		return Integer.parseInt(jedis.get(key));
	}
}
